package com.mall.config;

import com.mall.fliter.TokenAuthFilter;
import com.mall.fliter.TokenVerifyFilter;
import com.mall.security.*;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class TokenWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private TokenManager tokenManager;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private TokenLogoutHandler tokenLogoutHandler;
    @Resource
    private LoginSuccessHandler loginSuccessHandler;
    @Resource
    private LoginFailHandler loginFailHandler;
    @Resource
    private FilterInvocationSecurityMetadataSource urlFilterInvocationSecurityMetadataSource;
    @Resource
    private AccessDecisionManager urlAccessDecisionManager;
    @Resource
    private AccessDeniedHandler urlAccessDeniedHandler;
    @Resource
    private TokenVerifyFilter tokenVerifyFilter;


    /**
     * 配置设置
     * @param http
     * @throws Exception
     */
    //设置退出的地址和token，redis操作地址
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = http.antMatcher("/**").authorizeRequests();
        // url权限认证处理
        registry.withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
            @Override
            public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                o.setSecurityMetadataSource(urlFilterInvocationSecurityMetadataSource);
                o.setAccessDecisionManager(urlAccessDecisionManager);
                return o;
            }
        });
        // 登录过后访问无权限的接口时自定义响应内容
        http.exceptionHandling().accessDeniedHandler(urlAccessDeniedHandler);
        http//没有权限访问
                .cors().and().csrf().disable()
                .authorizeRequests()
                .antMatchers("/login","/user/logout").permitAll()
                .anyRequest().authenticated().and()
                .formLogin().loginProcessingUrl("/login")
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailHandler)
                .and().logout().logoutUrl("/user/logout")//退出路径
                .addLogoutHandler(tokenLogoutHandler)
                .and().exceptionHandling()
                .authenticationEntryPoint(new UnauthEntryPoint()).and()
                .addFilter(new TokenAuthFilter(authenticationManager(), tokenManager, redisTemplate))
                .addFilterBefore(tokenVerifyFilter, UsernamePasswordAuthenticationFilter.class);

    }

    //调用userDetailsService和密码处理
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new DefaultPasswordEncoder());
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

